package alexandria.dashboard.config

import grails.converters.deep.XML
import alexandria.dashboard.entity.*

class ConfigController {

    def connectorFactoryService

    /**
     * This action will redirect to the connector action for configure the dashboard
     * if the dashboard  is configured, it will render the configuration action
     **/
    def index = {
        if (!session.config) {
            redirect(action:"connectors")
        } else {
            // não tratado, apenas exibe session.config
            //redirect(action:"panel")
			redirect(controller:"panel")
        }
    }

    /**
     * This  action will render the connectors view that list all the avaliable connectors to the user
     **/
    def connectors = {
        session.config = null
        render(view:"connectors")
    }

   /**
    * This action will list all available projects in choose connector using the session config data to
    * obtain it.
    **/
    def projects = {
        if (!session.config) {
            redirect(action:"connectors")
        }else if(!session.config.token){
            flash.message = "Token can not be empty!"
            redirect(action:"connector", params:[name:"agilezen"])
        }else{
            try {
                def connector = connectorFactoryService.getConnector(session.config)
                [ projects: connector.listProjects() ]
            } catch (Exception e) {
                flash.message = "Could not connect to external data provider"
                redirect(action:"connector", params:[name:"agilezen"])
            }
        }
    }


    def connector = {
        def connectorName = params.name;
        session.config = [name: connectorName]
        render(view:"connector")
    }

    /** This action will set the param token into session cofiguration
     * @param token is the encryption key used for some REST requests
     * */
    def token = {
        session.config.put("token", params.token)
        redirect(action:"projects")
    }

    /* Essas ações são temporárias e sofrerão refatoração */

    /**
     * This action will convert the session configuration data in an XML file and render it
    **/
    def toxml = {
        def xml = session.config.encodeAsXML()
        render(text:xml,contentType:"text/xml",encoding:"UTF-8")
    }

    /**
     * This action will clean all session configuration data
    **/
    def undo = {
        session.config = null
        redirect(action:"index")
    }

    /** This action will set the param project_id into session configuration and render the dashboard
     * @param project_id is the id project cofigured to the dashboard
     * */
    def project = {
        if(!session.config.externalId){
            session.config.put("externalId", params['id'])
        }
        //redirect(action:"panel")
		redirect(controller:"panel")
    }

    def panel={

        //redirect(action: "toxml")
        //redirect(controller:"panel")

    }

}
